/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.epam.dbif;

import com.epam.dbif.object.Column;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ivan_Klyubanov
 */
public class DBAnalyser {
    
    private static final Logger LOG = Logger.getLogger(DBAnalyser.class.getName());
    
    public static Map<String, List<Column>> analyse(Connection connection) throws SQLException {        
        Map<String, List<Column>> tables = new HashMap<>();
        DatabaseMetaData metaData = connection.getMetaData();
        ResultSet resultSet = metaData.getTables(null, null, "%", null);
        String tableName = null;
        while(resultSet.next()) {
            tableName = resultSet.getString("TABLE_NAME");
            LOG.log(Level.INFO, "Table with name '" + tableName + "' was finded. Contains next columns... [");
            List<Column> columns = getColumns(metaData, tableName);
            LOG.log(Level.INFO, "]");
            tables.put(tableName, columns);            
        }
        return tables;
    }    

    public static List<Column> getColumns(DatabaseMetaData metaData, String tableName) throws SQLException {
        ResultSet columnResultSet = metaData.getColumns(null, null, tableName, "%");
        List<Column> columns = new ArrayList<>();
        Column column = null;
        while (columnResultSet.next()) {
            column = new Column(columnResultSet.getString("COLUMN_NAME"));
            column.setSize(columnResultSet.getInt("COLUMN_SIZE"));
            column.setTable(tableName);
            column.setType(columnResultSet.getInt("DATA_TYPE"));
            column.setTypeName(columnResultSet.getString("TYPE_NAME"));
            columns.add(column);
            LOG.log(Level.INFO, column.getName() + " " + column.getTypeName());
        }        
        return columns;
    }
    
    
}
